/**
 * AI Copilot 服务
 * 提供实时建议、智能补全、质量检测等功能
 */

import { CopilotSuggestion, QualityIssue } from '@/types/brainstorm';

interface SuggestionContext {
  selectedText: string;
  beforeText: string;
  afterText: string;
  paragraphType?: string;
  cursorPosition: number;
}

interface QualityScore {
  overall: number;
  originality: number;
  readability: number;
  information: number;
  emotion: number;
}

interface CompletionSuggestion {
  text: string;
  confidence: number;
}

/**
 * AI Copilot 服务类
 */
class AICopilotService {
  private ws: WebSocket | null = null;
  private suggestionCache = new Map<string, CopilotSuggestion[]>();
  private baseUrl: string;
  private isConnected: boolean = false;

  constructor() {
    this.baseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000';
  }

  /**
   * 初始化Copilot连接
   */
  async initCopilot(sessionId: string): Promise<void> {
    try {
      // 使用WebSocket进行实时通信
      const wsUrl = this.baseUrl.replace('http', 'ws');
      this.ws = new WebSocket(`${wsUrl}/ws/copilot/${sessionId}`);

      this.ws.onopen = () => {
        console.log('✅ [Copilot] Connected');
        this.isConnected = true;
      };

      this.ws.onmessage = (event) => {
        const data = JSON.parse(event.data);
        this.handleCopilotMessage(data);
      };

      this.ws.onerror = (error) => {
        console.error('❌ [Copilot] WebSocket error:', error);
      };

      this.ws.onclose = () => {
        console.log('🔌 [Copilot] Disconnected');
        this.isConnected = false;
      };
    } catch (error) {
      console.error('❌ [Copilot] Failed to initialize:', error);
      // 降级为使用HTTP API
    }
  }

  /**
   * 获取智能建议
   */
  async getSuggestions(context: SuggestionContext): Promise<CopilotSuggestion[]> {
    const cacheKey = this.generateCacheKey(context);

    // 检查缓存
    if (this.suggestionCache.has(cacheKey)) {
      return this.suggestionCache.get(cacheKey)!;
    }

    try {
      // 如果WebSocket连接可用，使用WebSocket
      if (this.ws && this.isConnected) {
        return await this.getSuggestionsViaWebSocket(context);
      }

      // 否则使用HTTP API
      return await this.getSuggestionsViaHttp(context);
    } catch (error) {
      console.error('❌ [Copilot] Failed to get suggestions:', error);
      // 返回本地生成的建议
      return this.generateLocalSuggestions(context);
    }
  }

  /**
   * 通过WebSocket获取建议
   */
  private async getSuggestionsViaWebSocket(context: SuggestionContext): Promise<CopilotSuggestion[]> {
    return new Promise((resolve) => {
      const requestId = Date.now().toString();

      // 设置响应处理器
      const handler = (event: MessageEvent) => {
        const data = JSON.parse(event.data);
        if (data.requestId === requestId && data.type === 'suggestions') {
          this.ws?.removeEventListener('message', handler);
          resolve(data.suggestions);
        }
      };

      this.ws?.addEventListener('message', handler);

      // 发送请求
      this.ws?.send(JSON.stringify({
        type: 'get_suggestions',
        requestId,
        context
      }));

      // 超时处理
      setTimeout(() => {
        this.ws?.removeEventListener('message', handler);
        resolve(this.generateLocalSuggestions(context));
      }, 3000);
    });
  }

  /**
   * 通过HTTP API获取建议
   */
  private async getSuggestionsViaHttp(context: SuggestionContext): Promise<CopilotSuggestion[]> {
    const response = await fetch(`${this.baseUrl}/api/v1/copilot/suggestions`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(context),
    });

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`);
    }

    const suggestions = await response.json();

    // 缓存结果
    const cacheKey = this.generateCacheKey(context);
    this.suggestionCache.set(cacheKey, suggestions);

    return suggestions;
  }

  /**
   * 生成本地建议（降级方案）
   */
  private generateLocalSuggestions(context: SuggestionContext): CopilotSuggestion[] {
    const suggestions: CopilotSuggestion[] = [];
    const { selectedText, beforeText, afterText } = context;

    // 1. 继续写下去
    if (!selectedText && beforeText) {
      suggestions.push({
        id: `suggestion-continue-${Date.now()}`,
        type: 'expand',
        title: '💡 继续写下去',
        description: '让AI帮你继续这个段落',
        action: 'continue',
        targetPosition: context.cursorPosition,
        priority: 'high',
        autoApplicable: true,
        createdAt: new Date().toISOString(),
      });
    }

    // 2. 扩展内容
    if (selectedText && selectedText.length < 100) {
      suggestions.push({
        id: `suggestion-expand-${Date.now()}`,
        type: 'expand',
        title: '🔍 深入展开',
        description: '展开这个观点，添加更多细节',
        action: 'expand',
        targetText: selectedText,
        priority: 'medium',
        autoApplicable: true,
        createdAt: new Date().toISOString(),
      });
    }

    // 3. 添加例子
    if (selectedText && this.isStatement(selectedText)) {
      suggestions.push({
        id: `suggestion-example-${Date.now()}`,
        type: 'add_example',
        title: '📖 添加案例',
        description: '为这个观点添加一个具体的例子',
        action: 'add_example',
        targetText: selectedText,
        priority: 'medium',
        autoApplicable: false,
        createdAt: new Date().toISOString(),
      });
    }

    // 4. 添加数据支撑
    if (selectedText && this.needsData(selectedText)) {
      suggestions.push({
        id: `suggestion-data-${Date.now()}`,
        type: 'add_data',
        title: '📊 添加数据',
        description: '添加相关的统计数据或研究结果',
        action: 'add_data',
        targetText: selectedText,
        priority: 'medium',
        autoApplicable: false,
        createdAt: new Date().toISOString(),
      });
    }

    // 5. 添加过渡
    if (this.needsTransition(beforeText, afterText)) {
      suggestions.push({
        id: `suggestion-transition-${Date.now()}`,
        type: 'add_transition',
        title: '🔗 添加过渡',
        description: '添加过渡句，使文章更连贯',
        action: 'add_transition',
        targetPosition: context.cursorPosition,
        priority: 'high',
        autoApplicable: true,
        createdAt: new Date().toISOString(),
      });
    }

    // 6. 简化表达
    if (selectedText && this.isComplex(selectedText)) {
      suggestions.push({
        id: `suggestion-simplify-${Date.now()}`,
        type: 'simplify',
        title: '✂️ 简化表达',
        description: '简化这段文字，使其更易理解',
        action: 'simplify',
        targetText: selectedText,
        priority: 'low',
        autoApplicable: true,
        createdAt: new Date().toISOString(),
      });
    }

    return suggestions;
  }

  /**
   * 获取智能补全
   */
  async getCompletion(context: {
    currentText: string;
    cursorPosition: number;
    paragraphContext: string;
  }): Promise<CompletionSuggestion[]> {
    try {
      const response = await fetch(`${this.baseUrl}/api/v1/copilot/completion`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(context),
      });

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}`);
      }

      return await response.json();
    } catch (error) {
      console.error('❌ [Copilot] Failed to get completion:', error);
      // 返回本地生成的补全
      return this.generateLocalCompletion(context);
    }
  }

  /**
   * 生成本地补全（降级方案）
   */
  private generateLocalCompletion(context: {
    currentText: string;
    cursorPosition: number;
    paragraphContext: string;
  }): CompletionSuggestion[] {
    const suggestions: CompletionSuggestion[] = [];

    // 获取光标前的文本
    const textBeforeCursor = context.currentText.substring(0, context.cursorPosition);
    const lastSentence = textBeforeCursor.split(/[。！？]/).pop() || '';

    // 简单的模式匹配补全
    const patterns = [
      { match: /因此$/, completions: ['，我们可以得出结论', '，这表明', '，需要注意的是'] },
      { match: /例如$/, completions: ['，在实际应用中', '，具体来说', '，我们可以看到'] },
      { match: /然而$/, completions: ['，事实上', '，另一方面', '，需要指出的是'] },
      { match: /首先$/, completions: ['，我们需要了解', '，让我们看看', '，重要的是'] },
      { match: /其次$/, completions: ['，值得注意的是', '，我们还需要考虑', '，另一个重要因素是'] },
      { match: /最后$/, completions: ['，总结来说', '，我们可以看出', '，综上所述'] },
    ];

    for (const pattern of patterns) {
      if (pattern.match.test(lastSentence)) {
        pattern.completions.forEach((text, index) => {
          suggestions.push({
            text,
            confidence: 0.9 - index * 0.1,
          });
        });
        break;
      }
    }

    // 如果没有匹配的模式，提供通用建议
    if (suggestions.length === 0 && lastSentence.length > 10) {
      suggestions.push(
        { text: '。', confidence: 0.5 },
        { text: '，这是一个重要的观点。', confidence: 0.4 },
        { text: '，值得我们深入思考。', confidence: 0.3 },
      );
    }

    return suggestions;
  }

  /**
   * 检测质量问题
   */
  async detectIssues(text: string): Promise<QualityIssue[]> {
    try {
      const response = await fetch(`${this.baseUrl}/api/v1/copilot/detect-issues`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ text }),
      });

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}`);
      }

      return await response.json();
    } catch (error) {
      console.error('❌ [Copilot] Failed to detect issues:', error);
      // 返回本地检测的问题
      return this.detectLocalIssues(text);
    }
  }

  /**
   * 本地质量问题检测
   */
  private detectLocalIssues(text: string): QualityIssue[] {
    const issues: QualityIssue[] = [];

    // 1. 检测重复内容
    const sentences = text.split(/[。！？]/);
    const seen = new Set<string>();

    sentences.forEach((sentence, index) => {
      const trimmed = sentence.trim();
      if (trimmed && seen.has(trimmed)) {
        issues.push({
          id: `issue-duplicate-${index}`,
          type: 'logic',
          severity: 'warning',
          message: '检测到重复的句子',
          position: {
            start: text.indexOf(sentence),
            end: text.indexOf(sentence) + sentence.length,
          },
          suggestion: '删除或改写重复的内容',
        });
      }
      seen.add(trimmed);
    });

    // 2. 检测过长句子
    sentences.forEach((sentence, index) => {
      if (sentence.length > 100) {
        issues.push({
          id: `issue-long-${index}`,
          type: 'readability',
          severity: 'info',
          message: '句子过长，可能影响可读性',
          position: {
            start: text.indexOf(sentence),
            end: text.indexOf(sentence) + sentence.length,
          },
          suggestion: '考虑将长句拆分为多个短句',
        });
      }
    });

    // 3. 检测逻辑跳跃
    for (let i = 0; i < sentences.length - 1; i++) {
      const current = sentences[i];
      const next = sentences[i + 1];

      if (this.hasLogicGap(current, next)) {
        issues.push({
          id: `issue-logic-${i}`,
          type: 'logic',
          severity: 'warning',
          message: '段落之间可能存在逻辑跳跃',
          position: {
            start: text.indexOf(next),
            end: text.indexOf(next) + Math.min(50, next.length),
          },
          suggestion: '添加过渡句或解释，使逻辑更连贯',
        });
      }
    }

    return issues;
  }

  /**
   * 获取质量评分
   */
  async getQualityScore(paragraphText: string): Promise<QualityScore> {
    try {
      const response = await fetch(`${this.baseUrl}/api/v1/copilot/quality-score`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ text: paragraphText }),
      });

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}`);
      }

      return await response.json();
    } catch (error) {
      console.error('❌ [Copilot] Failed to get quality score:', error);
      // 返回本地计算的评分
      return this.calculateLocalQualityScore(paragraphText);
    }
  }

  /**
   * 本地质量评分计算
   */
  private calculateLocalQualityScore(text: string): QualityScore {
    const wordCount = text.length;
    const sentences = text.split(/[。！？]/).filter(s => s.trim());
    const avgSentenceLength = sentences.reduce((sum, s) => sum + s.length, 0) / sentences.length;

    // 简单的评分逻辑
    const readability = Math.min(100, Math.max(0, 100 - Math.abs(avgSentenceLength - 30)));
    const information = Math.min(100, (wordCount / 10));
    const originality = 85; // 默认值，实际需要查重
    const emotion = this.hasEmotionalWords(text) ? 70 : 50;

    const overall = Math.round((readability + information + originality + emotion) / 4);

    return {
      overall,
      originality,
      readability,
      information,
      emotion,
    };
  }

  /**
   * 处理Copilot消息
   */
  private handleCopilotMessage(data: any): void {
    if (data.type === 'suggestion') {
      // 触发UI更新
      window.dispatchEvent(
        new CustomEvent('copilot-suggestion', { detail: data.suggestion })
      );
    } else if (data.type === 'quality-update') {
      // 更新质量评分
      window.dispatchEvent(
        new CustomEvent('copilot-quality', { detail: data.score })
      );
    }
  }

  /**
   * 生成缓存键
   */
  private generateCacheKey(context: SuggestionContext): string {
    return `${context.selectedText}_${context.paragraphType || 'default'}`;
  }

  /**
   * 辅助方法：判断是否是陈述句
   */
  private isStatement(text: string): boolean {
    return text.length > 20 && !text.endsWith('？');
  }

  /**
   * 辅助方法：判断是否需要数据支撑
   */
  private needsData(text: string): boolean {
    const dataKeywords = ['增长', '提升', '下降', '百分', '数据', '统计', '研究', '调查'];
    return dataKeywords.some(keyword => text.includes(keyword));
  }

  /**
   * 辅助方法：判断是否需要过渡
   */
  private needsTransition(before: string, after: string): boolean {
    if (!before || !after) return false;

    // 简单判断：如果前后文主题差异较大，可能需要过渡
    const beforeKeywords = this.extractSimpleKeywords(before);
    const afterKeywords = this.extractSimpleKeywords(after);

    const overlap = beforeKeywords.filter(k => afterKeywords.includes(k));
    return overlap.length < Math.min(beforeKeywords.length, afterKeywords.length) / 2;
  }

  /**
   * 辅助方法：判断文本是否复杂
   */
  private isComplex(text: string): boolean {
    // 包含多个从句或专业术语
    const complexIndicators = ['其中', '因此', '然而', '不仅', '而且', '虽然', '但是'];
    const complexCount = complexIndicators.filter(indicator => text.includes(indicator)).length;
    return complexCount > 2 || text.length > 150;
  }

  /**
   * 辅助方法：判断是否有逻辑断层
   */
  private hasLogicGap(sentence1: string, sentence2: string): boolean {
    const keywords1 = this.extractSimpleKeywords(sentence1);
    const keywords2 = this.extractSimpleKeywords(sentence2);

    // 如果两个句子的关键词完全不同，可能存在逻辑断层
    const overlap = keywords1.filter(k => keywords2.includes(k));
    return overlap.length === 0 && keywords1.length > 0 && keywords2.length > 0;
  }

  /**
   * 辅助方法：提取简单关键词
   */
  private extractSimpleKeywords(text: string): string[] {
    return text
      .split(/[，。！？、\s]/)
      .filter(word => word.length > 2)
      .slice(0, 5);
  }

  /**
   * 辅助方法：判断是否包含情感词
   */
  private hasEmotionalWords(text: string): boolean {
    const emotionalWords = ['喜欢', '讨厌', '开心', '难过', '激动', '失望', '美好', '糟糕', '惊喜', '遗憾'];
    return emotionalWords.some(word => text.includes(word));
  }

  /**
   * 清理资源
   */
  cleanup(): void {
    if (this.ws) {
      this.ws.close();
      this.ws = null;
    }
    this.suggestionCache.clear();
    this.isConnected = false;
  }
}

export const aiCopilotService = new AICopilotService();